//
//  MapViewController.m
//  Map
//
//  Created by 黄 晨 on 12-2-24.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "MapViewController.h"

@implementation MapViewController

@synthesize mapView, annotationArray;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Map";
    
	// Do any additional setup after loading the view, typically from a nib.
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    locationManager.distanceFilter = 1000;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
    
    self.mapView.delegate = self;
	// 是否显示当前位置
    self.mapView.showsUserLocation = YES;
    
    //长点击
    UILongPressGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longpress.minimumPressDuration = 0.5;//按0.5秒响应longPress方法
    longpress.allowableMovement = 10.0;
    [mapView addGestureRecognizer:longpress]; 
    
    self.annotationArray = [[NSMutableArray alloc] init];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

// 设置地图的类型
- (IBAction)setMapType:(id)sender
{
    switch (((UISegmentedControl *)sender).selectedSegmentIndex)
    {
            // 标准视图
        case 0:
        {
            mapView.mapType = MKMapTypeStandard;
            break;
        } 
            // 卫星视图
        case 1:
        {
            mapView.mapType = MKMapTypeSatellite;
            break;
        } 
            // 混合视图
        default:
        {
            mapView.mapType = MKMapTypeHybrid;
            break;
        } 
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"定位出错");
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [manager stopUpdatingLocation];
    
    NSLog(@"%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    coordinate.latitude = newLocation.coordinate.latitude;
    coordinate.longitude = newLocation.coordinate.longitude;
    
    //设置显示范围
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coordinate,1000 ,1000);  
    [self.mapView setRegion:region animated:TRUE];
}

- (void)locationAddressWithLocation:(CLLocation *)locationGps
{
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    geoCoder = clGeoCoder;
    
    [geoCoder reverseGeocodeLocation:locationGps completionHandler:^(NSArray *placemarks, NSError *error) 
     {
         NSLog(@"error %@ placemarks count %d", error.localizedDescription, placemarks.count);
         NSLog(@"%@", placemarks);
         for (CLPlacemark *placeMark in placemarks) 
         {
             CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithCoords:locationGps.coordinate];
             [annotation setPlaceMark:placeMark];
             [annotation setTitle:[NSString stringWithFormat:@"%@-%@", placeMark.locality, placeMark.subLocality]];
             [annotation setSubtitle:placeMark.thoroughfare];
             [annotation setTag:[self.annotationArray count]];
             
             [self.annotationArray addObject:annotation];
             
             [self.mapView addAnnotation:annotation];
         }
     }];
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView
            viewForAnnotation:(id <MKAnnotation>)annotation
{
    // 如果是显示当前地点，返回nil
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    
    // 如果注解是自定义注解
    if ([annotation isKindOfClass:[CustomAnnotation class]])
    {
        // 尝试从队列中移出存在的pinView
        MKPinAnnotationView *pinView = (MKPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomAnnotation"];
        
        if (!pinView)
        {
            pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomAnnotation"];
            pinView.canShowCallout = YES;
            pinView.animatesDrop = YES;
            
            UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];  
            [rightButton addTarget:self  
                            action:@selector(showDetails:)
                  forControlEvents:UIControlEventTouchUpInside];  
            pinView.rightCalloutAccessoryView = rightButton;
            UIImageView *headImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"flag.png"]];  
            pinView.leftCalloutAccessoryView = headImage;
            pinView.opaque = YES;  
        }
        else
        {
            pinView.annotation = annotation;
        }
        
        return pinView;
    }
    
    return nil;
}

- (void)longPress:(UIGestureRecognizer*)gestureRecognizer{
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
        return;
    }
    
    //坐标转换
    CGPoint touchPoint = [gestureRecognizer locationInView:mapView];
    CLLocationCoordinate2D touchMapCoordinate = [mapView convertPoint:touchPoint toCoordinateFromView:mapView];
    NSLog(@"%f,%f",touchMapCoordinate.latitude,touchMapCoordinate.longitude);
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:touchMapCoordinate.latitude longitude:touchMapCoordinate.longitude];
    
    [self locationAddressWithLocation:location];
}

- (void)showDetails:(id)sender
{
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailViewController.placeMark = ((CustomAnnotation *)[self.annotationArray objectAtIndex:[sender tag]]).placeMark;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
}

@end
